package web.sharedUI;

import java.io.IOException;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import ejb.userManagement.SessionMgr;


@ManagedBean
@RequestScoped
public class SessionBean {
	
	@EJB
	SessionMgr sessionMgr;
	
	/**
	 * Logout User
	 * @return redirect to Home
	 */
	public String logout() {
	    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
	    //redirect("/home.xhtml");
	    return "/home?faces-redirect=true";
	}
	
	/**
	 * Logged user name
	 * @return first name
	 */
	public String getName() {
		return sessionMgr.getUserFirstName();
	}
	
	/**
	 * Display an Error message
	 * @param error
	 */
	public static void displayError(String error) {
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ErrorMessage._BASIC, error));
	}
	
	/**
	 * Redirects user
	 * @param outcome xhtml page where to redirect user
	 */
	public static void redirect(String outcome) {
		try {
			FacesContext.getCurrentInstance().getExternalContext().dispatch(outcome);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//FacesContext facesContext = FacesContext.getCurrentInstance();
        //facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
	}
	
	public static void notFound() {
		try {
			FacesContext.getCurrentInstance().getExternalContext().dispatch("notFound.xhtml");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
